#!/bin/bash

# 确保必要工具存在
check_cmd() {
    command -v $1 >/dev/null 2>&1 || { echo "需要安装 $1"; exit 1; }
}
check_cmd docker
check_cmd mount

# 配置 - 全部在内存中操作
WORK_DIR=$(mktemp -d -p /tmp ssl_upload_XXXXXX)
mount -t tmpfs -o size=2G tmpfs "$WORK_DIR"
echo "创建全内存工作目录: $WORK_DIR"

# 证书源文件路径
CERT_SOURCE="/etc/acme/520613.crt"
KEY_SOURCE="/etc/acme/520613.key"

# 华为云镜像源配置
ALPINE_MIRROR="http://mirrors.huaweicloud.com/alpine"
PYPI_MIRROR="https://repo.huaweicloud.com/repository/pypi/simple"
ALPINE_VERSION="3.21"

# 腾讯云配置（必须替换为你的有效信息）
TC_SECRET_ID="请替换为实际SecretId"      # 请替换为实际SecretId
TC_SECRET_KEY="请替换为实际SecretKey"    # 请替换为实际SecretKey
TC_REGION="ap-guangzhou"         # 请替换为实际区域

# 检查证书文件是否存在
if [ ! -f "$CERT_SOURCE" ] || [ ! -f "$KEY_SOURCE" ]; then
    echo "错误: 证书文件不存在，请检查路径"
    umount "$WORK_DIR"
    rmdir "$WORK_DIR"
    exit 1
fi

# 创建Python脚本（内存中）
cat > "$WORK_DIR/upload_cert.py" <<EOF
import hmac
import hashlib
import json
import time
import datetime
import sys
import os
import requests
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.ssl.v20191205 import ssl_client, models

# 腾讯云配置
TC_SECRET_ID = os.getenv('TC_SECRET_ID', '$TC_SECRET_ID')
TC_SECRET_KEY = os.getenv('TC_SECRET_KEY', '$TC_SECRET_KEY')
TC_REGION = os.getenv('TC_REGION', '$TC_REGION')

# 读取证书内容
CERT_PATH = os.getenv('CERT_PATH', '/workdir/520613.crt')
KEY_PATH = os.getenv('KEY_PATH', '/workdir/520613.key')

try:
    with open(CERT_PATH, 'r', encoding='utf-8') as f:
        cert_content = f.read()
    with open(KEY_PATH, 'r', encoding='utf-8') as f:
        key_content = f.read()
except Exception as e:
    print(f"[ERROR] 读取证书文件失败: {e}")
    sys.exit(1)

# 生成时间戳和日期
timestamp = int(time.time())
utc_now = datetime.datetime.utcfromtimestamp(timestamp)
date = utc_now.strftime("%Y%m%d")
formatted_time = utc_now.strftime("%a, %d %b %Y %H:%M:%S GMT")

print(f"[DEBUG] UTC时间: {utc_now}")
print(f"[DEBUG] 时间戳: {timestamp}, 日期: {date}")
print(f"[DEBUG] RFC1123时间: {formatted_time}")

# 时间同步检查
def check_time_sync():
    try:
        response = requests.head('https://ssl.tencentcloudapi.com', timeout=5)
        server_date = response.headers.get('Date')
        if server_date:
            server_time = datetime.datetime.strptime(server_date, '%a, %d %b %Y %H:%M:%S GMT')
            time_diff = (utc_now - server_time).total_seconds()
            print(f"[DEBUG] 与服务器时间差: {time_diff:.2f}秒")
            if abs(time_diff) > 60:
                print("[WARNING] 时间偏差超过1分钟，可能导致签名失败！")
        else:
            print("[WARN] 未获取到服务器时间")
    except Exception as e:
        print(f"[DEBUG] 时间同步检查失败: {e}")

check_time_sync()

# 使用腾讯云官方SDK上传证书
try:
    cred = credential.Credential(TC_SECRET_ID, TC_SECRET_KEY)
    http_profile = HttpProfile()
    http_profile.endpoint = "ssl.tencentcloudapi.com"
    client_profile = ClientProfile()
    client_profile.httpProfile = http_profile
    client = ssl_client.SslClient(cred, TC_REGION, client_profile)
    
    req = models.UploadCertificateRequest()
    req.CertificatePublicKey = cert_content
    req.CertificatePrivateKey = key_content
    req.Alias = f"edgeone-cert-{int(time.time())}"
    
    print("[DEBUG] 使用腾讯云官方SDK发送请求...")
    resp = client.UploadCertificate(req)
    
    # 正确解析腾讯云响应（注意字段是CertificateId）
    print(f"[DEBUG] SDK响应: {resp.to_json_string()}")
    if hasattr(resp, "CertificateId") and resp.CertificateId:
        print(f"证书上传成功，CertId: {resp.CertificateId}")
        sys.exit(0)
    elif hasattr(resp, "Error") and resp.Error:
        err_msg = f"上传失败: {resp.Error.Code} - {resp.Error.Message}"
        print(f"[ERROR] {err_msg}")
        sys.exit(1)
    else:
        print(f"[ERROR] 未知响应格式: {resp.to_json_string()}")
        sys.exit(1)
        
except Exception as e:
    print(f"[ERROR] 异常发生: {e}")
    if hasattr(e, "request_id"):
        print(f"[DEBUG] 请求ID: {e.request_id}")
    if hasattr(e, "code") and hasattr(e, "message"):
        print(f"[DEBUG] 错误代码: {e.code}, 错误信息: {e.message}")
    sys.exit(1)
EOF

# 复制证书到内存目录
cp "$CERT_SOURCE" "$WORK_DIR/520613.crt" || { echo "证书复制失败"; cleanup; exit 1; }
cp "$KEY_SOURCE" "$WORK_DIR/520613.key" || { echo "私钥复制失败"; cleanup; exit 1; }

# 清理函数
cleanup() {
    umount "$WORK_DIR" 2>/dev/null
    rmdir "$WORK_DIR" 2>/dev/null
    docker system prune -f --volumes 2>/dev/null
    echo "已清理所有内存资源"
}
trap cleanup EXIT

# 显示内存目录内容
echo "内存目录文件列表:"
ls -la "$WORK_DIR"

# 全内存运行Docker容器 可以根据架构 --platform linux/arm64/v8 \
docker run --rm \
  --network=host \
  -v "$WORK_DIR:/workdir" \
  -e TC_SECRET_ID="$TC_SECRET_ID" \
  -e TC_SECRET_KEY="$TC_SECRET_KEY" \
  -e TC_REGION="$TC_REGION" \
  -e PYPI_MIRROR="$PYPI_MIRROR" \
  --tmpfs /var/lib/docker:size=2G \
  python:3.9-alpine3.21 \
  sh -c "echo '$ALPINE_MIRROR/v$ALPINE_VERSION/main' > /etc/apk/repositories && \
         echo '$ALPINE_MIRROR/v$ALPINE_VERSION/community' >> /etc/apk/repositories && \
         apk add --no-cache python3-dev libffi-dev openssl-dev build-base && \
         pip install --no-cache-dir -i \$PYPI_MIRROR requests tencentcloud-sdk-python && \
         python3 /workdir/upload_cert.py && \
         apk del python3-dev libffi-dev openssl-dev build-base"

exit $?